package com.kaiwukj.android.ufamily.mvp.ui.page.account.login.vcode;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.app.constant.SPParam;
import com.kaiwukj.android.ufamily.di.component.DaggerAccountComponent;
import com.kaiwukj.android.ufamily.di.module.AccountModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.LoginEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.VCodeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.requestbak.WechatLoginRequest;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.AccountContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.AccountPresenter;
import com.mob.secverify.CustomUIRegister;
import com.mob.secverify.OperationCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.VerifyCallback;
import com.mob.secverify.datatype.UiSettings;
import com.mob.secverify.datatype.VerifyResult;
import com.mob.secverify.exception.VerifyException;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.WebViewUrl;

@Route(path = ARouterUrlKt.CodeLoginRouterUrl)
public class LoginVCodeIndexActivity extends BaseMvpActivity<AccountPresenter> implements AccountContract.View {


    private String phoneNum;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    private int pos = 0;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerAccountComponent.builder()
                .appComponent(appComponent)
                .accountModule(new AccountModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_base_content;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadRootFragment(R.id.fl_content, LoginVCodeIndexFragment.newInstance(pos));
        boolean isFistShow = SPUtils.getInstance(SPParam.APP).getBoolean("first_agreement", true);
        if (isFistShow) {
            showAgreementDialog();
            SPUtils.getInstance(SPParam.APP).put("first_agreement", false);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        SecVerify.preVerify(new OperationCallback<Void>() {
            @Override
            public void onComplete(Void data) {
                LogUtils.d("秒验预登陆成功");
            }

            @Override
            public void onFailure(VerifyException e) {
                LogUtils.e("秒验预登陆失败:" + e.getCode() + ":" + e.getMessage());
            }
        });
    }

    @Subscribe
    public void onVCodeEvent(VCodeEvent event) {
        //loadRootFragment(R.id.fl_content, LoginVCodeIndexFragment.newInstance(++pos));
        //mPresenter.sendVerifyCode((String) event.getObj());
        if (event.getCode() == VCodeEvent.SEND) {
            phoneNum = (String) event.getObj();
            mPresenter.sendVerifyCode(phoneNum);
            start(LoginVCodeIndexFragment.newInstance(1, phoneNum));
        } else if (event.getCode() == VCodeEvent.RE_SEND) {
            phoneNum = (String) event.getObj();
            mPresenter.sendVerifyCode(phoneNum);
        } else if (event.getCode() == VCodeEvent.LOGIN_WECHAT) {
            loginWechat();
        } else if (event.getCode() == VCodeEvent.LOGIN_FAST) {
            loginFast();
        } else {
            mPresenter.loginByCode(phoneNum, (String) event.getObj());
        }
    }

    @Override
    public void loginSuccess() {
        if (getApp().getUserInfo().getLastCommunityId() == null || getApp().getUserInfo().getLastCommunityId() < 0) {
            ARouter.getInstance().build(ARouterUrlKt.CommunityUpdateUrl).navigation();
        } else {
            ARouter.getInstance().build(ARouterUrlKt.MainRouterUrl).navigation(this, new NavigationCallback() {
                @Override
                public void onFound(Postcard postcard) {

                }

                @Override
                public void onLost(Postcard postcard) {

                }

                @Override
                public void onArrival(Postcard postcard) {
                    finish();
                }

                @Override
                public void onInterrupt(Postcard postcard) {

                }
            });
        }
    }

    @Override
    public void wechatBindMobild(String openId) {
        hideLoading();
        ARouter.getInstance().build(ARouterUrlKt.ForgetPassUrl)
                .withInt("way", 1)
                .withString("extra", openId)
                .navigation();
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == AccountPresenter.VERIFY_CODE_SEND) {
            onVerifyCodeSendSuccess();
        }
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        if (taskId == AccountPresenter.VERIFY_CODE_SEND) {
            onVerifyCodeSendFailed();
        }
    }

    //验证码发送成功
    public void onVerifyCodeSendSuccess() {
        showMessage("发送成功");
        // start(LoginVCodeIndexFragment.newInstance(1));
    }

    //验证码发送成功
    public void onVerifyCodeSendFailed() {

    }

    private void showAgreementDialog() {
       /*QMUIDialog dialog =  new QMUIDialog.CustomDialogBuilder(this)
                .setLayout(R.layout.dialog_agreement)
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .create();*/
        //  dialog.

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog dialog = builder.create();
        View dialogView = View.inflate(this, R.layout.dialog_agreement, null);
        dialog.setView(dialogView);
        dialog.show();

        String content = getString(R.string.agreement_content);
        final TextView tvContent = dialog.findViewById(R.id.tv_content);

        SpannableString spannableString = new SpannableString(content);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                preAgreement(true);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(LoginVCodeIndexActivity.this, R.color.colorAccent));
                ds.setUnderlineText(false);
            }
        };

        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                preAgreement(false);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(LoginVCodeIndexActivity.this, R.color.colorAccent));
                ds.setUnderlineText(false);
            }
        };

        spannableString.setSpan(clickableSpan, content.length() - 26, content.length() - 20, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableString.setSpan(clickableSpan2, content.length() - 19, content.length() - 13, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        tvContent.setText(spannableString);
        tvContent.setMovementMethod(LinkMovementMethod.getInstance());
        tvContent.setHighlightColor(Color.TRANSPARENT);

        dialogView.findViewById(R.id.tv_to_protocol).setOnClickListener(v -> preAgreement(true));
        dialogView.findViewById(R.id.tv_to_protocol_private).setOnClickListener(v -> preAgreement(false));

        final Button btnConfirm = dialog.findViewById(R.id.btn_confirm);
        final CheckBox cbAgreement = dialogView.findViewById(R.id.cb_agreement);
        btnConfirm.setOnClickListener(v -> {
            if (cbAgreement.isChecked()) {
                dialog.dismiss();
            } else {
                showMessage("请先勾选同意");
            }
        });
    }

    private void preAgreement(boolean userAgreement) {
        if (userAgreement) {
            ARouter.getInstance().build(ARouterUrlKt.WebViewUrl)
                    .withString("EXTRA_KEY_WEB_URL", Constant.LOGIN_TIP_WEB_URL)
                    .withString("EXTRA_KEY_WEB_TITLE", "用户协议")
                    .navigation();
        } else {
            ARouter.getInstance().build(WebViewUrl)
                    .withString("EXTRA_KEY_WEB_URL", Constant.H5_PRIVACE)
                    .withString("EXTRA_KEY_WEB_TITLE", "隐私协议")
                    .navigation();
        }
    }

    private void loginWechat() {
        //loginType = 1;
        final IWXAPI api;
        api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
        //将应用的appid注册到微信
        api.registerApp(Constant.WX_APP_ID);
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_kaiwulink";
        if (!api.isWXAppInstalled()) {
            showMessage(getString(R.string.please_install_wechat));
            return;
        }
        api.sendReq(req);
    }


    private void loginFast() {
        fastLoginInit();
        SecVerify.verify(new VerifyCallback() {
            @Override
            public void onOtherLogin() {
                LogUtils.d("onOtherLogin");
            }

            @Override
            public void onUserCanceled() {
                LogUtils.d("onUserCanceled");
            }

            @Override
            public void onComplete(VerifyResult verifyResult) {
                mPresenter.loginByFast(verifyResult.getToken(), verifyResult.getOpToken(), verifyResult.getOperator());
            }

            @Override
            public void onFailure(VerifyException e) {
                LogUtils.e("onFailure:" + e.getCode() + ":" + e.getMessage());
                showMessage("" + e.getMessage() + "，请使用其它方式登录");
            }
        });
    }

    private void fastLoginInit() {
        UiSettings uiSettings = new UiSettings.Builder()
                .setNumberOffsetY(150)
                .setLoginBtnImgId(R.drawable.shape_login_default_btn)
                .setLoginBtnOffsetY(210)
                .setSwitchAccText("其他手机号码登录")
                .setSwitchAccTextSize(R.dimen.dp_15)
                .setSwitchAccHidden(true)
                //.setSwitchAccColorId(R.color.app_color_dark)
                .setSwitchAccOffsetY(280)
                .setAgreementColorId(-0x14a4a7)
                .setLogoImgId(R.mipmap.ic_fastlogin_logo)
                .setLogoHeight(43)
                .setLogoWidth(43)
                .setLogoOffsetY(100)
                .setCusAgreementNameId1("《用户协议》")
                .setCusAgreementUrl1(Constant.LOGIN_TIP_WEB_URL)
                .setAgreementTextAnd1("、")
                .setAgreementTextStart("登录/注册即表示同意")
                .setAgreementCmccText("《中国移动隐私协议》")
                .setAgreementCuccText("《中国联通隐私协议》")
                .setAgreementCtccText("《中国电信隐私协议》")
                .setAgreementTextEnd("并授权家院里获取本机号码")
                .setAgreementOffsetY(320)
                .build();

        List<View> viewList = new ArrayList<>();

        RelativeLayout containerTitle = new RelativeLayout(this);
        TextView textView = new TextView(this);
        textView.setText("您好");
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
        textView.setTextColor(ContextCompat.getColor(this, R.color.black_color));
        RelativeLayout.LayoutParams titleParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        titleParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        titleParams.setMargins(0, SizeUtils.dp2px(24), 0, 0);
        // containerTitle.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        containerTitle.setLayoutParams(titleParams);
        containerTitle.setGravity(Gravity.CENTER);
        containerTitle.addView(textView);

        viewList.add(containerTitle);

        View btnOtherPhone = View.inflate(this, R.layout.widget_fastlogin_other_btn, null);
        RelativeLayout.LayoutParams btnOtherPhoneParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                SizeUtils.dp2px(44f));
        btnOtherPhoneParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        btnOtherPhoneParams.setMargins(SizeUtils.dp2px(36f), SizeUtils.dp2px(260f), SizeUtils.dp2px(36f), 0);
        btnOtherPhone.setLayoutParams(btnOtherPhoneParams);

        btnOtherPhone.findViewById(R.id.btn_pass).setOnClickListener(v -> {
            SecVerify.finishOAuthPage();
            //  ARouter.getInstance().build(LoginRouterUrl).navigation()
        });

        View layoutFlag = View.inflate(this, R.layout.widget_fastlogin_other_flag, null);
        RelativeLayout.LayoutParams flagParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

        flagParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        flagParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        flagParams.setMargins(0, 0, 0, SizeUtils.dp2px(128f));
        layoutFlag.setLayoutParams(flagParams);

        View layoutOther = View.inflate(this, R.layout.widget_fastlogin_other, null);
        layoutOther.findViewById(R.id.iv_wechat).setOnClickListener(v -> loginWechat());
        //layoutOther.findViewById(R.id.iv_qq).setOnClickListener(v -> showMessage("QQ登录"));
        RelativeLayout.LayoutParams otherParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        otherParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        otherParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        otherParams.setMargins(0, 0, 0, SizeUtils.dp2px(80f));
        layoutOther.setLayoutParams(otherParams);

        viewList.add(btnOtherPhone);
        //viewList.add(layoutFlag);
        // viewList.add(layoutOther);
        CustomUIRegister.addCustomizedUi(viewList, null);
        SecVerify.setUiSettings(uiSettings);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        WechatLoginRequest wechatLoginRequest =
                new WechatLoginRequest(null, null, loginEvent.getOpenId());
        String mOpenId = loginEvent.getOpenId();
        mPresenter.loginByWechat(mOpenId, null, null);
        // mPresenter.wechatLogin(wechatLoginRequest);
    }


    private long lastMills;

    @Override
    public void onBackPressedSupport() {
        if (((LoginVCodeIndexFragment) getTopFragment()).getFlag() == 0 && System.currentTimeMillis() - lastMills > 1800) {
            showMessage("退出APP");
            lastMills = System.currentTimeMillis();
        } else {
            super.onBackPressedSupport();
        }
    }
}
